'''
Author: your name
Date: 2021-07-29 21:59:54
LastEditTime: 2021-07-29 21:59:55
LastEditors: your name
Description: In User Settings Edit
FilePath: \MyOpenmv\Optical_and_blob\OpticalFlow.py
'''
'''
Author: your name
Date: 2021-07-29 21:59:54
LastEditTime: 2021-07-29 21:59:54
LastEditors: your name
Description: In User Settings Edit
FilePath: \MyOpenmv\Optical_and_blob\OpticalFlow.py
'''
import time
import sensor, image, pyb

extra_fb = sensor.alloc_extra_fb(64, 64, sensor.RGB565)
#extra_fb.replace(sensor.snapshot().crop(x_size = 64, x_size = 64,roi = (0,0,64,64)))

sensor.skip_frames(time = 2000)     # 等待设置生效。
                # 创建一个时钟对象来跟踪FPS帧率。
def flowing(img):


    img.crop(x_scale = 0.4, y_scale = 0.4, x_size = 64, y_size = 64, roi = (40,0,160,160))
    #img.crop(x_size = 64, y_size = 64, roi = (120,80,64,64))

    displacement = extra_fb.find_displacement(img)
    extra_fb.replace(img)

    # 没有滤波，偏移结果是嘈杂的，所以我们降低了一些精度。
    sub_pixel_x = int(displacement.x_translation() * 5) / 5.0
    sub_pixel_y = int(displacement.y_translation() * 5) / 5.0

    #(intX, intY) = (127, 127)
    (intX, intY) = (int(sub_pixel_x / 10 * 127), int(sub_pixel_y / 10 * 127))

    if(displacement.response() > 0.1): # 低于0.1左右（YMMV），结果只是噪音。
        return (intX, intY, 1)
    return (0, 0, 0)

